import { login,getInfo, menu } from '@/api/userMG'
import { getToken, setToken, removeToken } from '@/utils/auth'

const getDefaultState = () => {
    //用于存储Token
    //用户名
    //用户头像
    //菜单列表
    return {
        token: getToken(),
        name: '',
        avatar: '',
        menuList: []
    }
}

const state = getDefaultState;


const actions = {
    // user/login登录请求
    login({ commit }, userInfo) {
        const { username, password, rememberMe } = userInfo
        return new Promise((resolve, reject) => {
            login({ username: username.trim(), password: password, rememberMe: rememberMe }).then(response => {
                console.log('登录login的值')
                console.log(response)
                const { data } = response
                commit('SET_TOKEN', data.token)
                setToken(data.token)
                resolve()

            }).catch(error => {
                reject(error)
            })
        })
    },
    // user info
    //用户登录根据permission
    //来判断是否需要获取用户姓名和头像
    getInfo({ commit,state }){
        return new Promise((resolve,reject) => {
            getInfo(state).then(response => {
                const { data } = response
                console.log('以获取用户姓名和头像')
                console.log(data)
                if(!data){
                    return reject('Verification failed, 验证失败')
                }

                const { name , avatar} = data
                commit('SET_AVATAR',avatar)
                commit('SET_NAME',name)
                resolve(data)
            }).catch(error => {
                reject(error)
            })
        })
    },
    resetToken({ commit }){
        return new Promise(resolve => {
            removeToken()  // must remove  token  first
            commit('RESET_STATE')
            resolve()
        })
    },
    getMenuList(){
        //获取菜单
        return new Promise((resolve,reject) =>{
            const { menuList } =  menu()
            // commit('SET_MENULIST',menuList)
                console.log('以获取到菜单列表')
                console.log(menuList)
                resolve(menuList)
        })
    }
}

const mutations = {
    RESET_STATE: (state) => {
        Object.assign(state, getDefaultState)
    },
    SET_TOKEN: (state, token) => {
        state.token = token
    },
    SET_NAME: (state, name) => {
        state.name = name
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar
    },
    SET_MENULIST: (state, menuList) => {
        state.menuList = menuList
    }
    ,
    //登录
    login(state, user) {
        state.user = user;
        localStorage.setItem("userInfo", user)
    },
    logout(state, user) {
        state.user = "";
        localStorage.setItem("userInfo", "");
    }
}

export default {
    namespaced: true,
    mutations,
    actions,
    state
}


